﻿using Microsoft.EntityFrameworkCore;

namespace EFCore1
{
  internal class Program
  {
    static async Task Main(string[] args)
    {
      using MyDbContext db = new();
      //db.Dogs.Add(new Dog { Name = "Tom" });//将新Dog对象添加到逻辑表里面

      //db.Dogs.Add(new Dog { Name = "Jerray" });
      //db.Persons.Add(new Person { Name = "Wangchao", Age = 19, Salary = 5000, BirthPlace = "Shenzhen" });
      //db.Books.Add(new Book { AuthorName = "李清照", Price = 23, PubTime = DateTime.Now, Title = "清明上河图" });

      //db.Books.Add(new Book { AuthorName = "叶峰", Price = 33, PubTime = new DateTime(2023,4,8), Title = "WPF实践" });
      //db.Books.Add(new Book { AuthorName = "叶峰", Price = 55, PubTime = new DateTime(2023,9,22), Title = "新能源与CT" });
      //db.Books.Add(new Book { AuthorName = "王羲之", Price = 27, PubTime = new DateTime(1690,6,8), Title = "大河向东流" });
      //db.Books.Add(new Book { AuthorName = "李白", Price = 66, PubTime = new DateTime(1032,7,15), Title = "天宫武装计划书" });

      //var books = db.Books.Where(a => a.Price > 50);
      //foreach (var book in books)
      //{
      //  Console.WriteLine(book.Title);
      //}
      //var bk = db.Books.Single(b => b.Title == "清明上河图");
      //Console.WriteLine(bk.AuthorName);

      //var b1=db.Books.OrderBy(a=> a.Price).Where(b=>b.Price>30);
      //foreach (var book in b1)
      //{
      //  Console.WriteLine(book.Title + " " + book.Price);
      //}

      //var books = db.Books.GroupBy(b => b.AuthorName).Select(g => new { Name = g.Key, BookCount = g.Count(), MaxPrice = g.Max(b => b.Price) });

      //foreach (var book in books)
      //{
      //  Console.WriteLine($"Name:{book.Name},BookCount:{book.BookCount},MaxPrice:{book.MaxPrice}");
      //}

      //var b = db.Books.Where(a => a.Price >20);
      //b.AuthorName = "叶峰";

      var d1 = db.Dogs.Single(a => a.Name == "Jerray");
      var d = db.Dogs.Where(a => a.Name == "Jerray");
      //db.Dogs.Remove(d);
      Console.WriteLine(d.ToQueryString()); //只能获取查询语句的操作
      //await db.DeleteRangeAsync<Book>(a => a.Price > 50 || a.AuthorName == "李清照");//杨中科写的快速删改数据的EFCore的拓展包
      //await db.BatchUpdate<Person>()
      //     .Set(a => a.Salary, a => a.Salary + 1000)
      //     .Set(a => a.Age, a => a.Age + 10)
      //     .ExecuteAsync();

      //db.Persons.Where(a=>a.Salary>4000).ExecuteUpdate(a=>a.SetProperty(a=>a.Salary,a=>a.Salary+1000)); //EF7之后可以通过 ExecuteUpdate ExecuteDelete来快速批量删改数据
      //await db.Dogs.Where(a => a.Name == "Tom").ExecuteDeleteAsync();

      //var a = db.Birds.Add(new Bird { Name = "xx"/*, Id = Guid.NewGuid()*/ });//当Guid作为主键时，可以提前指定Id
      //Console.WriteLine(a.Entity.Id);



      //有数据表更新时通过 Add-Migration Add_Cat 来build Migrations的类 ，通过 Update-Database 更新数据库

      await db.SaveChangesAsync();// Update-Database

    }
  }
}
